import { useState } from 'react';
import { 
    Box, 
    Button, 
    Typography, 
    Paper,
    Grid,
    FormControlLabel,
    Checkbox,
    Slider,
    IconButton,
    Tooltip,
    Alert,
    LinearProgress
} from '@mui/material';
import ToolPageTemplate from '@/components/ToolPageTemplate';
import VpnKeyIcon from '@mui/icons-material/VpnKey';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import RefreshIcon from '@mui/icons-material/Refresh';

const PasswordGenPage = () => {
    const [length, setLength] = useState(12);
    const [includeUppercase, setIncludeUppercase] = useState(true);
    const [includeLowercase, setIncludeLowercase] = useState(true);
    const [includeNumbers, setIncludeNumbers] = useState(true);
    const [includeSymbols, setIncludeSymbols] = useState(false);
    const [excludeSimilar, setExcludeSimilar] = useState(true);
    const [password, setPassword] = useState('');
    const [copied, setCopied] = useState(false);

    const calculateStrength = () => {
        let score = 0;
        if (length >= 8) score += 1;
        if (length >= 12) score += 1;
        if (includeUppercase) score += 1;
        if (includeLowercase) score += 1;
        if (includeNumbers) score += 1;
        if (includeSymbols) score += 1;
        return Math.min(score, 5);
    };

    const getStrengthText = (strength: number) => {
        const texts = ['很弱', '弱', '一般', '强', '很强', '极强'];
        return texts[strength] || '很弱';
    };

    const getStrengthColor = (strength: number) => {
        const colors = ['error', 'error', 'warning', 'info', 'success', 'success'];
        return colors[strength] || 'error';
    };

    const generatePassword = () => {
        let charset = '';
        if (includeUppercase) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        if (includeLowercase) charset += 'abcdefghijklmnopqrstuvwxyz';
        if (includeNumbers) charset += '0123456789';
        if (includeSymbols) charset += '!@#$%^&*()_+-=[]{}|;:,.<>?';
        
        if (excludeSimilar) {
            charset = charset.replace(/[0O1lI]/g, '');
        }

        if (!charset) {
            setPassword('');
            return;
        }

        let result = '';
        for (let i = 0; i < length; i++) {
            result += charset.charAt(Math.floor(Math.random() * charset.length));
        }
        setPassword(result);
    };

    const copyToClipboard = () => {
        if (password) {
            navigator.clipboard.writeText(password);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        }
    };

    const strength = calculateStrength();

    return (
        <ToolPageTemplate 
            title="密码生成器"
            description="生成安全的随机密码，可自定义长度和字符规则"
            category="安全工具"
            categoryColor="#d32f2f"
        >
            <Grid container spacing={4}>
                <Grid item xs={12} md={6}>
                    <Box sx={{ mb: 3 }}>
                        <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>
                            密码设置
                        </Typography>
                        
                        <Box sx={{ mb: 3 }}>
                            <Typography variant="body1" sx={{ mb: 2 }}>
                                密码长度: {length}
                            </Typography>
                            <Slider
                                value={length}
                                onChange={(_, value) => setLength(value as number)}
                                min={4}
                                max={64}
                                step={1}
                                valueLabelDisplay="auto"
                            />
                        </Box>

                        <Typography variant="body1" sx={{ mb: 2, fontWeight: 600 }}>
                            字符类型
                        </Typography>
                        
                        <FormControlLabel
                            control={
                                <Checkbox 
                                    checked={includeUppercase} 
                                    onChange={(e) => setIncludeUppercase(e.target.checked)} 
                                />
                            }
                            label="大写字母 (A-Z)"
                        />
                        
                        <FormControlLabel
                            control={
                                <Checkbox 
                                    checked={includeLowercase} 
                                    onChange={(e) => setIncludeLowercase(e.target.checked)} 
                                />
                            }
                            label="小写字母 (a-z)"
                        />
                        
                        <FormControlLabel
                            control={
                                <Checkbox 
                                    checked={includeNumbers} 
                                    onChange={(e) => setIncludeNumbers(e.target.checked)} 
                                />
                            }
                            label="数字 (0-9)"
                        />
                        
                        <FormControlLabel
                            control={
                                <Checkbox 
                                    checked={includeSymbols} 
                                    onChange={(e) => setIncludeSymbols(e.target.checked)} 
                                />
                            }
                            label="特殊符号 (!@#$%...)"
                        />

                        <Box sx={{ mt: 2 }}>
                            <FormControlLabel
                                control={
                                    <Checkbox 
                                        checked={excludeSimilar} 
                                        onChange={(e) => setExcludeSimilar(e.target.checked)} 
                                    />
                                }
                                label="排除相似字符 (0, O, 1, l, I)"
                            />
                        </Box>

                        <Button 
                            variant="contained" 
                            size="large"
                            startIcon={<VpnKeyIcon />}
                            onClick={generatePassword}
                            fullWidth
                            sx={{ mt: 3 }}
                            disabled={!includeUppercase && !includeLowercase && !includeNumbers && !includeSymbols}
                        >
                            生成密码
                        </Button>
                    </Box>
                </Grid>

                <Grid item xs={12} md={6}>
                    <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>
                        生成的密码
                    </Typography>

                    {copied && (
                        <Alert severity="success" sx={{ mb: 2 }}>
                            密码已复制到剪贴板
                        </Alert>
                    )}

                    {password ? (
                        <Box>
                            <Paper 
                                elevation={0}
                                sx={{ 
                                    p: 3, 
                                    mb: 3,
                                    bgcolor: 'grey.50',
                                    border: '1px solid',
                                    borderColor: 'grey.300',
                                    position: 'relative'
                                }}
                            >
                                <Typography 
                                    variant="h6" 
                                    component="code"
                                    sx={{ 
                                        fontFamily: 'monospace',
                                        wordBreak: 'break-all',
                                        display: 'block',
                                        mb: 2,
                                        fontSize: '1.1rem'
                                    }}
                                >
                                    {password}
                                </Typography>
                                
                                <Box sx={{ display: 'flex', gap: 1 }}>
                                    <Tooltip title="复制密码">
                                        <IconButton onClick={copyToClipboard}>
                                            <ContentCopyIcon />
                                        </IconButton>
                                    </Tooltip>
                                    <Tooltip title="重新生成">
                                        <IconButton onClick={generatePassword}>
                                            <RefreshIcon />
                                        </IconButton>
                                    </Tooltip>
                                </Box>
                            </Paper>

                            <Box>
                                <Typography variant="body1" sx={{ mb: 1, fontWeight: 600 }}>
                                    密码强度: {getStrengthText(strength)}
                                </Typography>
                                <LinearProgress 
                                    variant="determinate" 
                                    value={(strength / 5) * 100}
                                    color={getStrengthColor(strength) as any}
                                    sx={{ height: 8, borderRadius: 4 }}
                                />
                            </Box>
                        </Box>
                    ) : (
                        <Paper 
                            elevation={0}
                            sx={{ 
                                p: 4, 
                                textAlign: 'center',
                                bgcolor: 'grey.50',
                                minHeight: 200,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                border: '2px dashed',
                                borderColor: 'grey.300'
                            }}
                        >
                            <Box>
                                <VpnKeyIcon sx={{ fontSize: 60, color: 'grey.400', mb: 2 }} />
                                <Typography variant="body1" color="text.secondary">
                                    点击生成按钮创建安全密码
                                </Typography>
                            </Box>
                        </Paper>
                    )}
                </Grid>
            </Grid>
        </ToolPageTemplate>
    );
};

export default PasswordGenPage;